package jp.co.sharp.android.parents.kidsguard.activity.setting;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.res.ResourcesCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONObject;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

/**
 * 権限付与
 */
public class AuthorityActivity extends Activity {

    private App mApp;
    private KidInfoEntity mKidInfoEntity;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    private DelDeviceConfirmDlg mDelDeviceConfirmDlg;
    private ParentBleTransfer mParentBleTransfer;
    private Button mSubmitBtn;
    private Switch mPhoneBookSw;
    private Switch mScheduleSw;
    private Switch mAlarmSw;
    private Switch mQuickCallSw;
    private Switch mProfileSw;
    private OldInitActivity mOldInitActivity;
    /** 0: lock, 0: init , 1: getInfo , 2: setInfo, 3 :end */
    private int mViewProcess = 0;
    private boolean mScreenOperate = false;
    private boolean mUnReceiver = true;
    /** ページジャンプ */
    private boolean mPageJumpFlag = false;
    /** システムホームプレス*/
    private boolean mSystemHomeFlag = false;
    private static final String TAG = "TAG";
    /** プログラムロック */
    private final String mSyncLock = "syncLock";
    /** 編集を再開しています... */
    private boolean mEditReopening = false;
    private static final int PAGE_EDIT_REOPEN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "AuthorityActivity_onCreate");
        setContentView(R.layout.activity_authority);

        mApp = (App)getApplication();
        initReceiver();
        initActivity();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "AuthorityActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if (mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT) {
                    Message msg = new Message();
                    msg.what = PAGE_EDIT_REOPEN;
                    handler.sendMessage(msg);
                }
                mSystemHomeFlag = false;
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "PowerSettingActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    protected void onStop() {
        Log.i(TAG, "AuthorityActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG, "AuthorityActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
            }
            mUnReceiver = true;
        }
        super.onDestroy();
    }

    private void initActivity() {
        Log.i(TAG, "AuthorityActivity_initActivity");
        mKidInfoEntity = mApp.findKidInfoBySelect();

        TextView textView = (TextView)findViewById(R.id.settingSecondMenu);
        String strSecondMenu = mKidInfoEntity.getKidName() + "のキッズケータイ";
        textView.setText(strSecondMenu);

        mPhoneBookSw = (Switch)findViewById(R.id.swPhoneBook);
        mScheduleSw = (Switch)findViewById(R.id.swSchedule);
        mAlarmSw = (Switch)findViewById(R.id.swAlarm);
        mQuickCallSw = (Switch)findViewById(R.id.swQuickCall);
        mProfileSw = (Switch)findViewById(R.id.swProfile);

        mSubmitBtn = (Button)findViewById(R.id.submitBtn);
        mSubmitBtn.setEnabled(false);
        mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));

        initListener();

        // Dlg
        String message = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(AuthorityActivity.this, R.style.commonDlg, message, true);
        mDealWithWaitingDlg.show();
        // Get
        mViewProcess = Constants.SEND_KID_IS_USING;
        new BusinessThread(Constants.SEND_KID_IS_USING,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
    }

    private void initListener() {
        mSubmitBtn.setOnClickListener(v -> {
            if (mSubmitBtn.isEnabled()) {
                // Dlg
                String message = "キッズケータイへ反映中..";
                mDealWithWaitingDlg = new DealWithWaitingDlg(AuthorityActivity.this, R.style.commonDlg, message, true);
                mDealWithWaitingDlg.show();

                setAuthority();
            }
        });

        mPhoneBookSw.setOnCheckedChangeListener((compoundButton, b) -> {
            if (!mPhoneBookSw.isPressed()) {
                return;
            }
            if (checkSubmit()) {
                mSubmitBtn.setEnabled(true);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
            } else {
                mSubmitBtn.setEnabled(false);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
            }
        });

        mScheduleSw.setOnCheckedChangeListener((compoundButton, b) -> {
            if (!mScheduleSw.isPressed()) {
                return;
            }
            if (checkSubmit()) {
                mSubmitBtn.setEnabled(true);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
            } else {
                mSubmitBtn.setEnabled(false);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
            }
        });

        mAlarmSw.setOnCheckedChangeListener((compoundButton, b) -> {
            if (!mAlarmSw.isPressed()) {
                return;
            }
            if (checkSubmit()) {
                mSubmitBtn.setEnabled(true);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
            } else {
                mSubmitBtn.setEnabled(false);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
            }
        });

        mQuickCallSw.setOnCheckedChangeListener((compoundButton, b) -> {
            if (!mQuickCallSw.isPressed()) {
                return;
            }
            if (checkSubmit()) {
                mSubmitBtn.setEnabled(true);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
            } else {
                mSubmitBtn.setEnabled(false);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
            }
        });

        mProfileSw.setOnCheckedChangeListener((compoundButton, b) -> {
            if (!mProfileSw.isPressed()) {
                return;
            }
            if (checkSubmit()) {
                mSubmitBtn.setEnabled(true);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_change, null));
            } else {
                mSubmitBtn.setEnabled(false);
                mSubmitBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_reflect_normal, null));
            }
        });
    }


    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(TAG, "AuthorityActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        // ロック画面
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 画面を開く
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App)getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }


    class OldInitActivity {
        boolean mSwPhoneBook = false;
        boolean mSwSchedule = false;
        boolean mSwAlarm = false;
        boolean mSwQuickCall = false;
        boolean mSwProfile = false;
    }

    private boolean checkSubmit() {
        Log.i(TAG, "AuthorityActivity_checkSubmit");
        return !(mOldInitActivity.mSwPhoneBook == mPhoneBookSw.isChecked() &&
                mOldInitActivity.mSwSchedule == mScheduleSw.isChecked() &&
                mOldInitActivity.mSwAlarm == mAlarmSw.isChecked() &&
                mOldInitActivity.mSwQuickCall == mQuickCallSw.isChecked() &&
                mOldInitActivity.mSwProfile == mProfileSw.isChecked());
    }

    /**
     *
     */
    private void setAuthority() {
        Log.i(TAG, "AuthorityActivity_setAuthority");
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", RequestMethodConstants.METHOD_SET_AUTHORIZATION);
            JSONObject jsonData = new JSONObject();
            if (mPhoneBookSw.isChecked()) {
                jsonData.put("phoneBook", 0);
            } else {
                jsonData.put("phoneBook", 1);
            }
            if (mScheduleSw.isChecked()) {
                jsonData.put("schedule", 0);
            } else {
                jsonData.put("schedule", 1);
            }
            if (mAlarmSw.isChecked()) {
                jsonData.put("alarm", 0);
            } else {
                jsonData.put("alarm", 1);
            }
            if (mQuickCallSw.isChecked()) {
                jsonData.put("quickCall", 0);
            } else {
                jsonData.put("quickCall", 1);
            }
            if (mProfileSw.isChecked()) {
                jsonData.put("profile", 0);
            } else {
                jsonData.put("profile", 1);
            }

            jsonObject.put("data", jsonData);
            mViewProcess = Constants.SEND_KID_SET_INFO;
            new BusinessThread(Constants.SEND_KID_SET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            Message msg = new Message();
                            msg.what = PAGE_EDIT_REOPEN;
                            handler.sendMessage(msg);
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    // 初期化
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (mApp.isMimamoriCheck(macAddress)) {
                        mApp.addmLsIsMimamori(macAddress);
                        // TODO Mimamori
                        mViewProcess = Constants.SEND_KID_EXIT;
                        new BusinessThread(Constants.SEND_KID_EXIT,
                                mParentBleTransfer,
                                mKidInfoEntity,
                                null,
                                PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();

                        // ページジャンプ
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(AuthorityActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        mApp.updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AuthorityActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(() -> {
                            processWarringDlg.dismiss();
                            // ページジャンプ
                            mPageJumpFlag = true;
                            Intent intent1 = new Intent();
                            intent1.setClass(AuthorityActivity.this, SettingActivity.class);
                            startActivity(intent1);
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                 if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    if (bluetoothReceiverDto.isFinished()) {
                        switch(mViewProcess) {

                            case Constants.SEND_KID_ENTER:
                                if (!mScreenOperate) {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("method", RequestMethodConstants.METHOD_GET_AUTHORIZATION);
                                    jsonObject.put("data", JSONObject.NULL);
                                    mViewProcess = Constants.SEND_KID_GET_INFO;
                                    new BusinessThread(Constants.SEND_KID_GET_INFO,
                                            mParentBleTransfer,
                                            mKidInfoEntity,
                                            jsonObject,
                                            PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
                                } else {
                                    mEditReopening = false;
                                    mScreenOperate = false;
                                    handler.sendEmptyMessage(0);
                                }
                                break;
                            case Constants.SEND_KID_EXIT:
                                if (null != mDelDeviceConfirmDlg && mDealWithWaitingDlg.isShowing()) {
                                    mDelDeviceConfirmDlg.dismiss();
                                }
                                if (!mScreenOperate) {
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    AuthorityActivity.this.finish();
                                } else if (!mSystemHomeFlag) {
                                    // ページジャンプ
                                    mPageJumpFlag = true;
                                    Intent intent1 = new Intent();
                                    intent1.setClass(AuthorityActivity.this, SettingActivity.class);
                                    startActivity(intent1);
                                }
                                break;
                            case Constants.SEND_KID_IS_USING:
                            case Constants.SEND_KID_GET_INFO:
                            case Constants.SEND_KID_SET_INFO:
                            default:
                                break;
                        }
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String retStr = bluetoothReceiverDto.getRetStr();
                    JSONObject jsonObject = new JSONObject(retStr);
                    if (RequestMethodConstants.METHOD_GET_AUTHORIZATION.equals(jsonObject.getString("method"))) {
                        try {
                            mOldInitActivity = new OldInitActivity();
                            JSONObject jsonData = jsonObject.getJSONObject("data");
                            if (jsonData.getInt("phoneBook") == 0) {
                                mPhoneBookSw.setChecked(true);
                                mOldInitActivity.mSwPhoneBook = true;
                            } else {
                                mPhoneBookSw.setChecked(false);
                            }
                            if (jsonData.getInt("schedule") == 0) {
                                mScheduleSw.setChecked(true);
                                mOldInitActivity.mSwSchedule = true;
                            } else {
                                mScheduleSw.setChecked(false);
                            }
                            if (jsonData.getInt("alarm") == 0) {
                                mAlarmSw.setChecked(true);
                                mOldInitActivity.mSwAlarm = true;
                            } else {
                                mAlarmSw.setChecked(false);
                            }
                            if (jsonData.getInt("quickCall") == 0) {
                                mQuickCallSw.setChecked(true);
                                mOldInitActivity.mSwQuickCall = true;
                            } else {
                                mQuickCallSw.setChecked(false);
                            }
                            if (jsonData.getInt("profile") == 0) {
                                mProfileSw.setChecked(true);
                                mOldInitActivity.mSwProfile = true;
                            } else {
                                mProfileSw.setChecked(false);
                            }

                            handler.sendEmptyMessage(0);
                        } catch (Exception e) {

                        }
                    } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getString("result").equals(Constants.ON_SYNC_RESULT)) {
                            handler.sendEmptyMessage(0);
                            mViewProcess = Constants.SEND_KID_EXIT;
                            new BusinessThread(Constants.SEND_KID_EXIT,
                                    mParentBleTransfer,
                                    mKidInfoEntity,
                                    null,
                                    PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
                        } else {
                            handler.sendEmptyMessage(0);
                            String message = "キッズケータイへ反映できませんでした";
                            ProcessWarningDlg processWarningDlg = new ProcessWarningDlg(AuthorityActivity.this, R.style.commonDlg, message);
                            processWarningDlg.show();
                            processWarningDlg.setOnOperateSetListener(processWarningDlg::dismiss);
                        }
                    } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(jsonObject.getString("method"))) {
                        String message = "キッズケータイが操作されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AuthorityActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(() -> {
                            processWarringDlg.dismiss();
                            // ページジャンプ
                            mPageJumpFlag = true;
                            AuthorityActivity.this.finish();
                        });
                    } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(jsonObject.getString("method"))) {
                        if (jsonObject.getJSONObject("data").getString("state").equals(Constants.IS_USING_OK)) {
                            mViewProcess = Constants.SEND_KID_ENTER;
                            new BusinessThread(Constants.SEND_KID_ENTER, mParentBleTransfer, mKidInfoEntity, null, PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
                        } else {
                            handler.sendEmptyMessage(0);
                            String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(AuthorityActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(() -> {
                                processWarringDlg.dismiss();
                                // ページジャンプ
                                mPageJumpFlag = true;
                                AuthorityActivity.this.finish();
                            });
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * Dialog閉じる
     */
    private Handler handler = new Handler(msg -> {
        if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
            mDealWithWaitingDlg.dismiss();
        } else if (msg.what == PAGE_EDIT_REOPEN) {
            if (!mEditReopening) {
                String message = "編集を再開しています...";
                mDealWithWaitingDlg = new DealWithWaitingDlg(AuthorityActivity.this, R.style.commonDlg, message, false);
                mDealWithWaitingDlg.show();
                mScreenOperate = true;
                mViewProcess = Constants.SEND_KID_IS_USING;
                new BusinessThread(Constants.SEND_KID_IS_USING,
                        mParentBleTransfer,
                        mKidInfoEntity,
                        null,
                        PageSerialNumConstants.PAGE_SERIAL_NUM_POWER_SETTING).start();
                // ブロードキャストの再登録
                unregisterReceiver(systemReceiver);
                initReceiver();
                mEditReopening = true;
            }
        }
        return false;
    });

    /**
     * ページリターンキー、フルスクリーンリターンジェスチャー
     */
    @Override
    public void onBackPressed() {
        backActivity(null);
    }

    /**
     * 前のページに戻る(値なし)
     */
    public void backActivity(View view) {
        Log.i(TAG, "AuthorityActivity_backActivity");
        if (!checkSubmit()) {
            mViewProcess = Constants.SEND_KID_EXIT;
            new BusinessThread(Constants.SEND_KID_EXIT, mParentBleTransfer, mKidInfoEntity, null, PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
        } else {
            String message = "編集内容は保存されていません。編集内容を破棄して前の画面に戻りますか？";
            mDelDeviceConfirmDlg = new DelDeviceConfirmDlg(AuthorityActivity.this, R.style.commonDlg, message);
            mDelDeviceConfirmDlg.show();
            mDelDeviceConfirmDlg.setOnOperateSetListener(() -> {
                mDelDeviceConfirmDlg.dismiss();
                mViewProcess = Constants.SEND_KID_EXIT;
                new BusinessThread(Constants.SEND_KID_EXIT, mParentBleTransfer, mKidInfoEntity, null, PageSerialNumConstants.PAGE_SERIAL_NUM_AUTHORITY).start();
            });
        }
    }
}
